<template>
  <el-form
    :model="formData"
    ref="formRef"
    @submit.prevent
    :rules="formRules"
    label-width="100px"
  >
    <el-row>
      <el-col>
        <el-form-item label="名称" prop="kyName">
          <el-input v-model.trim="formData.kyName"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-form-item label="编号" prop="kyNum">
          <el-input v-model.trim="formData.kyNum"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-form-item label="描述" prop="kyDesc">
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
            v-model="formData.kyDesc"
          ></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-form-item label="成果来源" prop="kyTypeCode">
          <el-select
            v-model="formData.kyTypeCode"
            clearable
            style="width: 100%"
            value-key="dicCode"
          >
            <el-option
              v-for="item in kyTypeArr"
              :key="item.dicCode"
              :label="item.dicValue"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-form-item label="上传文档" prop="kyAttachmentArr">
          <el-upload
            name="uploadFile"
            multiple
            :accept="acceptTypes"
            :action="uploadComUrl"
            :headers="uploadHeaders"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :on-error="handleError"
            :file-list="defaultFileList"
            :before-upload="beforeAvatarUpload"
            :on-preview="handlePreview"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持上传doc、docx、xls、xlsx、pdf、ppt、pptx、png、jpg、jpeg等格式文件,文件大小不得大于10M。
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <el-row justify="end">
    <el-button @click="handleCancel">取 消</el-button>
    <el-button type="primary" @click="handleSubmit">确 定</el-button>
  </el-row>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { cloneDeep } from "lodash-es";
import { useRoute } from "vue-router";
import { postScientificAdd, postScientificUpdate } from "/@/api/scientific";
import { postDictList } from "/@/api/common";
import NotifMessage from "/@/utils/message/notification";
import { useUpload } from "/@/hooks";

const handlePreview = (item: any) => {
  window.open(
    `${location.origin}${location.pathname}#/online?uuidFile=${item?.response.data.uuidFile}&fileName=${item?.response.data.fileName}`
  );
};
const {
  handleError,
  beforeAvatarUpload,
  uploadComUrl,
  acceptTypes,
  uploadHeaders,
  onInitFileList
} = useUpload();

const props = defineProps({
  mode: {
    type: String,
    default: "Add"
  },
  info: {
    type: Object,
    default: () => {}
  }
});

const emit = defineEmits(["emitSubmit", "update:dialogFormVisible"]);

const route = useRoute();

const formRef = ref<HTMLFormElement | null>(null) as any;

let formData = reactive({
  kyName: "",
  kyNum: "",
  kyDesc: "",
  kyTypeCode: null,
  kyTypeName: "",
  kyAttachmentArr: []
});

let kyTypeArr = ref([]);

const formRules = ref({
  kyName: [{ required: true, message: "请输入名称", trigger: "change" }],
  kyNum: [{ required: true, message: "请输入编号", trigger: "change" }],
  kyDesc: [{ required: true, message: "请输入描述", trigger: "change" }],
  kyTypeCode: [{ required: true, message: "请选择类型", trigger: "change" }],
  kyAttachmentArr: [
    { required: true, message: "请上传附件", trigger: "change" }
  ]
});

/* 上传 -- start */

let defaultFileList = ref([]);

const handleRemove = (file, fileList) => {
  defaultFileList.value = fileList;
  formData.kyAttachmentArr = formData.kyAttachmentArr.filter(item => {
    const uuid = file.response ? file.response.data.uuidFile : file.uuidFile;
    return item.uuidFile !== uuid;
  });
};

const handleSuccess = (res, file, fileList) => {
  if (res.code === 200) {
    defaultFileList.value = fileList;
    formData.kyAttachmentArr.push(res.data);
  }
  formRef.value.clearValidate();
};

/* 上传 -- end */

// 初始化请求
const initKyTypeList = async () => {
  try {
    const params = {
      dicType: "rd_ky_result_type"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      kyTypeArr.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

const handleSubmit = async (): Promise<any> => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (!isValid) return;
  try {
    const copyFormData = cloneDeep(formData);
    copyFormData.kyTypeCode = formData.kyTypeCode.dicCode;
    copyFormData.kyTypeName = formData.kyTypeCode.dicValue;

    copyFormData.projectManageId = route.query?.id ?? "";
    if (props.mode === "Add") {
      const { code, message } = await postScientificAdd(copyFormData);
      if (code === 200) {
        NotifMessage.success(message);
        emit("emitSubmit");
      } else {
        NotifMessage.error(message);
      }
    } else {
      copyFormData.id = props.info.id;
      const { code, message } = await postScientificUpdate(copyFormData);
      if (code === 200) {
        NotifMessage.success(message);
        emit("emitSubmit");
      } else {
        NotifMessage.error(message);
      }
    }
  } catch (err) {
    console.log(err);
  }
};

const handleCancel = () => {
  emit("update:dialogFormVisible", false);
};

onMounted(() => {
  if (props.mode === "Edit") {
    const { kyName, kyNum, kyDesc, kyTypeCode, kyTypeName, kyAttachmentArr } =
      cloneDeep(props.info);
    formData.kyName = kyName;
    formData.kyNum = kyNum;
    formData.kyDesc = kyDesc;
    formData.kyTypeCode = {
      dicCode: kyTypeCode,
      dicValue: kyTypeName
    };
    formData.kyTypeName = kyTypeName;
    formData.kyAttachmentArr = kyAttachmentArr;

    defaultFileList.value = onInitFileList(kyAttachmentArr);
  }
});

initKyTypeList();
</script>

<style lang="scss" scoped></style>
